package observerpattern;

import java.util.ArrayList;
import java.util.List;

/**
 * 具体被观察者类实现
 * Created by hongc on 2017/2/26 0026.
 */
public class ConcreteSubject implements Subject{
    //存储注册的观察者列表
    private List<Observer> observers  = new ArrayList<Observer>();
    //目标对象状态
    private String subjectState;

    public String getSubjectState() {
        return subjectState;
    }
    public void setSubjectState(String subjectState) {
        this.subjectState = subjectState;
        //当目标自身状态发生改变时，通知观察者
        this.notifyObservers();
    }

    @Override
    public void attach(Observer observer) {
        observers.add(observer);
    }

    @Override
    public void detach(Observer observer) {
        observers.remove(observer);
    }

    //向所有注册的观察者发送消息
    @Override
    public void notifyObservers() {
        for(Observer observer:observers){
            observer.update(this);
        }
    }
}
